<?php

if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );

/**
 * Class webservice
 * @author HuyThien
 *
 */
class Webservice extends MY_Controller {

    public function __construct() {
        parent::__construct();
    }

    /*
	 * function: login
	 * if we login with facebookid: if not exist, create new profile.
	 * param: email
	 * param: password
	 * param: facebookid
	 * return JSON: userId
	 */ 
	function login($request){
		$params = $this->getParams( $request );
		$result = array( 'error' => '-1', 'msg' => 'Login Failed!' );
		$this->load->model( 'user/user_model' );
		if($params['email']){
			if($params['password'])
				$params['password'] = $this->encode_pwd($params['password']);
			if($userId = $this->user_model->checkLogin( $params['email'], $params['password'] ) ){
				$result = array('error' => 0, 'msg' => 'Login success','userId' => $userId);
			}else{
				$result = array('error' => '-1', 'msg' => 'Email or Password wrong');
			}
		}elseif($params['facebookid']){
			if($userId = $this->user_model->loginWithFace($params['facebookid']) ){
				$result = array('error' => 0, 'msg' => 'Login success','userId' => $userId);
			}else{
				$data = array('facebookid' => $params['facebookid']);
				$userId = $this->user_model->insert($data);
				$result = array('error' => 0, 'msg' => 'Login success','userId' => $userId);
			}
		}
		return $this->responseSuccess( $result );
	}
	/*
	 * function: getPassword
	* get new password for user login.
	* param: email
	* return JSON: new password
	*/
	function getPassword($request){
		$params = $this->getParams( $request );
		$result = array( 'error' => '-1', 'msg' => 'Login Failed!' );
		$this->load->model( 'user/user_model' );
		$where = array("email" => $params['email']);
		$rows = $this->user_model->find_all_where($where);
		$result = array();
		if(count($rows)){
			$row = $rows[0];
			$pass = $this->createPassword();
			$data['password'] = $this->encode_pwd($pass);
			$userId = $this->user_model->update($row->id,$data);
			$result = array('user_id' => $row->id, 'email' => $row->email,'password'=> $pass);
		}
		return $this->responseSuccess( $result );
	}
	/**
	 * Get all category 
	 * @param unknown_type $request
	 * @return string
	 */
	function getCategorys($request){
		$result = array();
		$params = $this->getParams( $request );
		
		$this->load->model( 'category/category_model' );
		$this->load->model( 'provider/provider_model' );
		$this->load->model( 'product/product_model' );
		$result = array( 'error' => '0' );
		$data = $this->category_model->find_all($sort = 'register_date', $order = 'desc');
		$result['categorys'] = $data;
		$data = $this->provider_model->find_all($sort = 'register_date', $order = 'desc');
		$result['providers'] = $data;
		$data = $this->product_model->getWithProvider();
		$result['products'] = $data;
		return $this->responseSuccess( $result );
		
	}    

	function register( $request){
		$params = $this->getParams( $request );
		$result = array( 'error' => '0' );
		$this->load->model( 'user/user_model' );
		
		$data =  array( 'username'  => $params['email'],
				'email' => $params['email'],
				);
		if($params['password'])
			$data['password'] = $this->encode_pwd($params['password']);
		// Add new user
		if ( $id = $this->user_model->insert( $data ) ){
			$result['userId'] = $id; 
			$result['msg'] = 'Insert OK';
		}else
			$result['msg'] = 'Insert failed';
			
		return $this->responseSuccess( $result );
	}
	
	function updateProfile( $request){
		$params = $this->getParams( $request );
		$error = $this->checkAuth( $params );
		if ( $error < 0 ) {
			return $this->responseError( $error );
		}
		$result = array( 'error' => '0' );
		$this->load->model( 'member/member_model' );
		
		$data =  array( 'gender'  => $params['gender'],
				'first_name' => $params['first_name'],
				'last_name' => $params['last_name'],
				'insertion' => $params['insertion'],
				'address' => $params['address'],
				'house_number' => $params['house_number'],
				'postcode' => $params['postcode'],
				'place' => $params['place'],
				'email' => $params['email'],
				'phone' => $params['phone'],
				'birthday' => $params['birthday']
				);
		if($params['password'])
			$data['password'] = $this->encode_pwd($params['password']);
		// Add new user
		if ( $this->member_model->update( $params['id'], $data ) ){
			$result['msg'] = 'Update OK';
		}else
			$result['msg'] = 'Update failed';
		return $this->responseSuccess( $result );
	}
	function addMember( $request){
		$params = $this->getParams( $request );
		$userId = $this->checkAuth( $params );
		if ( $userId < 0 ) {
			return $this->responseError( $userId );
		}
		$result = array( 'error' => '0' );
		$this->load->model( 'member/member_model' );
		
		$data =  array( 'gender'  => $params['gender'],
				'first_name' => $params['first_name'],
				'last_name' => $params['last_name'],
				'insertion' => $params['insertion'],
				'address' => $params['address'],
				'house_number' => $params['house_number'],
				'postcode' => $params['postcode'],
				'place' => $params['place'],
				'email' => $params['email'],
				'phone' => $params['phone'],
				'birthday' => $params['birthday'],
				'owner' => $userId,
				'death' => 0,
				'status' => 0 );
		// Add new user
		if ( $id = $this->member_model->insert( $data ) ){
			$result['userId'] = $id;
			$result['msg'] = 'Insert OK';
		}else
			$result['msg'] = 'Insert failed';
			
		return $this->responseSuccess( $result );
	}
	function updateMember( $request){
		$params = $this->getParams( $request );
		$userId = $this->checkAuth( $params );
		if ( $userId < 0 ) {
			return $this->responseError( $userId );
		}
		$result = array( 'error' => '0' );
		$this->load->model( 'member/member_model' );
		
		$data =  array( 'gender'  => $params['gender'],
				'first_name' => $params['first_name'],
				'last_name' => $params['last_name'],
				'insertion' => $params['insertion'],
				'address' => $params['address'],
				'house_number' => $params['house_number'],
				'postcode' => $params['postcode'],
				'place' => $params['place'],
				'email' => $params['email'],
				'phone' => $params['phone'],
				'birthday' => $params['birthday']
		);
		// Add new user
		if ( $this->member_model->update( $params['id'], $data ) ){
			$result['msg'] = 'Update OK';
		}else
			$result['msg'] = 'Update failed';
		return $this->responseSuccess( $result );
	}
	
	/*
	 * getProfile
	 * get profile info
	 * param: id
	 * return object of member
	 */
	function getProfile( $request ){
		$params = $this->getParams( $request );
		$userId = $this->checkAuth( $params );
		if ( $userId < 0 ) {
			return $this->responseError( $userId );
		}
		$result = array( 'error' => '0' );
		$this->load->model( 'member/member_model' );
		$data = $this->member_model->find_id($params['id']);
		//$data = $params['userId'];
		$result['profile'] = $data;
		return $this->responseSuccess( $result );
	}
	
	/*
	 * getListProfile
	 * get list member of one onwer.
	 * param: userId
	 * return: list members.
	 */
	function getListProfile( $request ){
		$params = $this->getParams( $request );
		$userId = $this->checkAuth( $params );
		if ( $userId < 0 ) {
			return $this->responseError( $userId );
		}
		$result = array( 'error' => '0' );
		$this->load->model( 'member/member_model' );
		$data = $this->member_model->getAllByOwner($userId);
		$result['members'] = $data;
		return $this->responseSuccess( $result );
	}
	
	/*
	 * addContract
	 * param: member_id, contract_number, category_id, provider_id, product_id, start_date, end_date
	 * return: error:0 or -1; msg; contractId.
	 */
	function addContract( $request){
		$params = $this->getParams( $request );
		$userId = $this->checkAuth( $params );
		if ( $userId < 0 ) {
			return $this->responseError( $userId );
		}
		$result = array( 'error' => '0' );
		$this->load->model( 'contract/contract_model' );
		
		$data =  array( 'member_id'  => $params['member_id'],
				'contract_number' => $params['contract_number'],
				'category_id' => $params['category_id'],
				'provider_id' => $params['provider_id'],
				'product_id' => $params['product_id'],
				'start_date' => $params['start_date'],
				'end_date' => $params['end_date']
		);
		// Add new user
		if ( $this->contract_model->insert( $data ) ){
			$result['msg'] = 'INsert OK';
		}else
			$result['msg'] = 'Insert failed';
		return $this->responseSuccess( $result );
	}
	
	/*
	 * getContract
	 * get contract detail 
	 */
	function getContract($request){
		$params = $this->getParams( $request );
		$error = $this->checkAuth( $params );
		if ( $error < 0 ) {
			return $this->responseError( $error );
		}
		$result = array( 'error' => '0' );
		$this->load->model( 'contract/contract_model' );
		$data =  $this->contract_model->find_id( $params['id'] );
		$result['contract'] = $data;
		return $this->responseSuccess( $result );
	}
	/*
	 * getListContract
	 * get list all contract of one member
	 * param: member_id
	 * return list all contract
	 */
	function getListContract( $request){
		$params = $this->getParams( $request );
		$error = $this->checkAuth( $params );
		if ( $error < 0 ) {
			return $this->responseError( $error );
		}
		$result = array( 'error' => '0' );
		$this->load->model( 'contract/contract_model' );
		$arr['member_id'] = $params['member_id'];
		$data =  $this->contract_model->getSearch( $arr );
		$result['contracts'] = $data;
		return $this->responseSuccess( $result );
	}
	
	function setTerminationAlert( $request){
		$params = $this->getParams( $request );
		$error = $this->checkAuth( $params );
		if ( $error < 0 ) {
			return $this->responseError( $error );
		}
		$result = array( 'error' => '0' );
		$this->load->model( 'contract/contract_model' );
		$id = $params['contract_id'];
		$arr['termination_date'] = $params['termination_date'];
		$arr['termination_alert'] = 1;
		$this->contract_model->update($id, $arr );
		$result['status'] = "Set termination alert for contract.";
		return $this->responseSuccess( $result );
	}
	
	function setDeath( $request){
		$params = $this->getParams( $request );
		$error = $this->checkAuth( $params );
		if ( $error < 0 ) {
			return $this->responseError( $error );
		}
		$result = array( 'error' => '0' );
		$this->load->model( 'member/member_model' );
		$id = $params['profile_id'];
		$arr['death'] = 1;
		$this->member_model->update($id, $arr );
		$result['status'] = "Set Death for Member.";
		return $this->responseSuccess( $result );
	}
	
	function sendDocument( $request){
		$params = $this->getParams( $request );
		$error = $this->checkAuth( $params );
		if ( $error < 0 ) {
			return $this->responseError( $error );
		}
		$result = array( 'error' => '0' );
		$this->load->model( 'category/category_model' );
		$this->load->model( 'product/product_model' );
		$this->load->model( 'provider/provider_model' );
		$this->load->model( 'member/member_model' );
		$type = $params['type'];
		$category_id = $params['category_id'];
		$provider_id = $params['provider_id'];
		$product_id = $params['product_id'];
		$member_id = $params['member_id'];
		$contract_number = $params['contract_number'];
		$category = $this->category_model->find_id($category_id);
		$product = $this->product_model->find_id($product_id);
		$provider = $this->provider_model->find_id($provider_id);
		$member = $this->member_model->find_id($member_id);
		$content = $category->content_letter;
		$content = str_replace('[CATEGORY_NAME]', $category->category_name, $content);
		$content = str_replace('[PROVIDER_NAME]', $provider->provider_name, $content);
		$content = str_replace('[PRODUCT_NAME]', $product->product_name, $content);
		$content = str_replace('[CONTRACT_NUMBER]', $contract_number, $content);
		$content = str_replace('[USER_EMAIL]', $member->email, $content);
		$content = str_replace('[FIRST_NAME]', $member->first_name, $content);
		$content = str_replace('[LAST_NAME]', $member->last_name, $content);
		$content = str_replace('[ADDRESS]', $member->address, $content);
		$content = str_replace('[HOUSE_NUMBER]', $member->house_number, $content);
		$content = str_replace('[POSTCODE]', $member->postcode, $content);
		$content = str_replace('[PLACE]', $member->place, $content);
		$result['status'] = "Sent document to user.";
		return $this->responseSuccess( $result );
	}
	/*
	 * changeAddress
	 * param: member_id, address, postcode, place, date
	 * return: 
	 */
	function changeAddress( $request){
		$params = $this->getParams( $request );
		$error = $this->checkAuth( $params );
		if ( $error < 0 ) {
			return $this->responseError( $error );
		}
		$result = array( 'error' => '0' );
		$this->load->model( 'member/member_move_model' );
		
		$data =  array( 'member_id'  => $params['member_id'],
				'address' => $params['address'],
				'postcode' => $params['postcode'],
				'place' => $params['place'],
				'date_move' => $params['date_move']
		);
		// Add new user
		if ( $this->member_move_model->insert( $data ) ){
			$result['msg'] = 'Insert OK';
		}else
			$result['msg'] = 'Insert failed';
		return $this->responseSuccess( $result );
	}
	function addTerminalLetter( $request){
		$params = $this->getParams( $request );
		$error = $this->checkAuth( $params );
		if ( $error < 0 ) {
			return $this->responseError( $error );
		}
		
		$result = array( 'error' => '0' );
	}
    /**
     *
     *
     * @param unknown $params
     * @return int
     */
    private function checkAuth( $params ) {
        // check params authenticate
        if ( !( isset( $params['username'] ) && isset( $params['passwd'] ) ) ) {
            return -1;
        }
        // check authenticate
        $this->load->model( 'user/user_model' );
        $result = $this->user_model->checkLogin( $params['username'], $this->encode_pwd( $params['passwd'] ) );
        if ( isset( $result->id ) && $result->id > 0  ) {
            return $result->id;
        }
        return  -2;
    }

    /**
     *
     *
     * @param unknown $data
     * @return string
     */
    private function responseSuccess( $data ) {
        $res =  array(
            'error'=>0,
            'data'=>$data
        );
        return json_encode( $data, true );
    }

    /**
     *
     *
     * @param unknown $errorCode
     * @return string
     */
    private function responseError( $errorCode ) {
        $msg = '';
        switch ( $errorCode ) {
        case -1:
            $msg = 'Invalid data';
            break;

        case -2:
            $msg = 'Authenticate Failure';
            break;
        }
        return json_encode( array( 'error'=>$errorCode, 'msg'=>$msg ), true );
    }

    /**
     *
     *
     * @param unknown $request
     * @return mixed
     */
    private function getParams( $request ) {
        return json_decode( $request, true );
    }

    /**
     * Zip one by one file
     *
     * @param unknown_type $arraycontents
     * @param unknown_type $pathfolder
     * @param unknown_type $filename
     */
    public function zipFile( $arraycontents, $pathfolder, $filename, $reserved_path = false, $keep_last = false ) {
        $this->load->library( 'zip' );
        foreach ( $arraycontents as $url ) {
            $this->zip->read_file( $url, $reserved_path, $keep_last );
        }
        $pathzip = $pathfolder."/".$filename.".zip";
        $this->zip->archive( $pathzip );
    }
}
